<template>
  <!-- 场景-规则配置 -->
  <div class="resultScene-data">
    <el-row class="ruleSceneNode container">
      <el-col style="margin-right:10px;" class="content-left" :span="ruleLeftWidth">
        <!-- 操作区域 -->
        <upper-template :searchIcon="false" :configIcon="false" :per="{left:24,right:0}"
        >
          <!-- 操作按钮区 -->
          <template slot="buttonArea"  v-if="operateType !='3'">
            <el-button @click="nodeAddFunc('1')">新增</el-button>
            <el-button @click="nodeAddFunc('2')">编辑</el-button>
            <el-button @click="editCancel">取消编辑</el-button>
            <el-button @click="delNodeFunc">删除</el-button>
            <el-button @click="nodeAddFunc('5')">复制</el-button>
            <el-button @click="saveSceneNode">保存</el-button>
          </template>
        </upper-template>
        <el-table ref="multipleSceneNodeTable" :data="tableSceneNodeData" style="width: 100%" @row-click="authorizeForSceneNode">
          <el-table-column
            width="55"
            type="selection"
          ></el-table-column>
          <el-table-column
            prop="nodeCode"
            label="英文名"
            :show-overflow-tooltip="true"
            v-if="columnSceneNodeState[0]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.saveData=='新增'">
                  <el-input
                    v-model="addNodeData.nodeCode"
                    maxlength="30"
                    minlength="1"
                    @blur="checkBasicNodeCode"
                  ></el-input>
              </div>
              <div v-if="scope.row.saveData=='编辑'">
                <el-input
                    v-model="scope.row.nodeCode"
                    maxlength="30"
                    minlength="1"
                    disabled
                  ></el-input>
              </div>
              <div v-if="scope.row.saveData=='复制'">
                <el-input
                    v-model="copyNodeData.nodeCode"
                    maxlength="30"
                    minlength="1"
                  ></el-input>
              </div>
              <div v-if="!scope.row.saveData">{{scope.row.nodeCode}}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="nodeName"
            label="中文名 "
            show-overflow-tooltip
            v-if="columnSceneNodeState[1]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.saveData=='新增'">
                  <el-input
                    v-model="addNodeData.nodeName"
                    maxlength="30"
                  ></el-input>
              </div>
              <div v-if="scope.row.saveData=='编辑'">
                <el-input
                    v-model="scope.row.nodeName"
                    maxlength="30"
                  ></el-input>
              </div>
              <div v-if="scope.row.saveData=='复制'">
                <el-input
                    v-model="copyNodeData.nodeName"
                    maxlength="30"
                  ></el-input>
              </div>
              <div v-if="!scope.row.saveData">{{scope.row.nodeName}}</div>
            </template>
          </el-table-column>

          <el-table-column
            prop="parentNode"
            label="上级节点 "
            :show-overflow-tooltip="true"
            v-if="columnSceneNodeState[2]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.saveData=='新增'">
                  <el-select
                    v-model="addNodeData.parentNode"
                    maxlength="200"
                  >
                    <el-option v-for="item in parentNodeList"
                      :key="item.nodeCode"
                      :label="item.nodeName"
                      :value="item.nodeCode">
                    </el-option>
                  </el-select>
              </div>
              <div v-if="scope.row.saveData=='编辑'">
                <el-select
                    v-model="scope.row.parentNode"
                    maxlength="200"
                  >
                    <el-option v-for="item in parentNodeList"
                      :key="item.nodeCode"
                      :label="item.nodeName"
                      :value="item.nodeCode">
                    </el-option>
                  </el-select>
              </div>
              <div v-if="scope.row.saveData=='复制'">
                <el-select
                    v-model="copyNodeData.parentNode"
                    maxlength="200"
                  >
                    <el-option v-for="item in parentNodeList"
                      :key="item.nodeCode"
                      :label="item.nodeName"
                      :value="item.nodeCode">
                    </el-option>
                  </el-select>
              </div>
              <div v-if="!scope.row.saveData">{{scope.row.parentName}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="descn"
            label="节点描述 "
            :show-overflow-tooltip="true"
            v-if="columnSceneNodeState[3]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.saveData=='新增'">
                  <el-input
                    v-model="addNodeData.descn"
                    maxlength="200"
                  ></el-input>
              </div>
              <div v-if="scope.row.saveData=='编辑'">
                <el-input
                    v-model="scope.row.descn"
                    maxlength="200"
                  ></el-input>
              </div>
              <div v-if="scope.row.saveData=='复制'">
                <el-input
                    v-model="copyNodeData.descn"
                    maxlength="200"
                  ></el-input>
              </div>
              <div v-if="!scope.row.saveData">{{scope.row.descn}}</div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          @size-change="handleSceneNodeSizeChange"
          @current-change="handleSceneNodeCurrentChange"
          :current-page="searchSceneNodeForm.page"
          :page-size="searchSceneNodeForm.size"
          @refresh="searchSceneNodeFunc"
          :total="resultSceneTotal"
        ></pagination>
      </el-col>
      <div class="icon-arrow">
        <i class="el-icon-d-arrow-right" @click="hideRule" v-if="hideRuleIcon"></i>
        <i class="el-icon-d-arrow-left" @click="showRule" v-if="showRuleIcon"></i>
      </div>
      <el-col v-if="ruleCon" style="margin-left:40px;" :span="11" :offset="1">
        <el-row class="title" style="margin: 15px 0;">
          <span class="gun"></span>
          规则配置
        </el-row>
        <el-row style="margin-bottom:20px;">
          <el-transfer
            :data="ruleDatas"
            filterable
            filter-placeholder="请输入规则名称"
            :titles="['备选','已选']"
            :props="{
              key:'ruleCode',
              label:'ruleName'
            }"
            v-model="selectRule"
          ></el-transfer>
        </el-row>
        <el-row style="margin-left:430px;" v-if="operateType != 3">
          <el-button style="margin-bottom:20px;" @click="saveRuleNode">保存</el-button>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ruleScene } from "@/api/index";
import upperTemplate from "@/components/upperTemplate.vue"
import onlyOneSearch from "@/components/onlyOneSearch";
import moment from "moment";
export default {
  data() {
    return {
      hideRuleIcon:true,
      showRuleIcon:false,
      ruleCon:true,
      ruleLeftWidth:12,
      // 列隐藏依据数据
      textSceneNodeData: [
        { prop: "nodeCode", label: "英文名", disabled: true },
        { prop: "nodeName", label: "中文名", disabled: true },
        { prop: "nodeName", label: "上级节点", disabled: true },
        { prop: "descn", label: "节点描述", disabled: true }
      ],
      // 显示的列
      checkSceneNodeList: [],
      //查询时默认条件
      searchSceneNodeForm: {
        page: 1,
        size: 15
      },
      //总条数
      resultSceneTotal: 0,
      tableSceneNodeData: [],
      //规则
      ruleDatas:[],
      selectRule:[],
      nodeCode:"",
      nodeSaveFlag:"1",
      //添加节点数据
      addNodeData: {
        nodeCode: '',
        nodeName: '',
        ruleSceneCode: '',
        parentNode: '',
        descn: '',
        saveData: '新增'
      },
      //复制节点数据
      copyNodeData: {
        nodeCode: '',
        nodeName: '',
        ruleSceneCode: '',
        parentNode: '',
        descn: '',
        saveData: '复制'
      },
      //父级节点数据
      parentNodeList: [],
      //验证节点编码是否存在
      checkNode: false
    };
  },
  props: {
    sceneCode: {
      type: String,
      default: ""
    },
    operateType: {
      type: String,
      default: "1"
    }
  },
  watch: {
    sceneCode: function(newVal, oldVal) {
      this.sceneCode = newVal;
      newVal&&this.searchSceneNodeFunc();
    },
    operateType: function(newVal, oldVal) {
      this.operateType = newVal;
      newVal&&this.searchSceneNodeFunc();
    },
    nodeCode: function(newVal, oldVal) {
      if (newVal.length > 0) {
        this.changeRule();
      }
    }
  },
  components: {
    onlyOneSearch
  },
  created() {
    //初始化显示的列
    this.checkSceneNodeListInit();
  },
  computed: {
    columnSceneNodeState() {
      let arr = [],
        arr1 = this.textSceneNodeData,
        arr2 = this.checkSceneNodeList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    },
    sceneCodeStatus: function() {
      return this.sceneCode;
    }
  },
  mounted() {
    this.searchSceneNodeFunc()
  },
  methods: {
    checkSceneNodeListInit() {
      this.checkSceneNodeList = this.textSceneNodeData.map(v => {
        return v.label;
      });
    },
    searchSceneNodeFunc() {
      this.ruleDatas = [];
      if (this.sceneCode.length != 0) {
        let data= {
          sceneCode:this.sceneCode,
          ...this.searchSceneNodeForm
        }
        ruleScene.getRuleNodeDetail(data).then(res => {
          if (res.code === 200) {
            this.tableSceneNodeData = res.datas.rows;
            this.resultSceneTotal = res.datas.total;
          }
        });
      } else {
        this.tableSceneNodeData = [];
        this.resultSceneTotal = 0;
      }
      //this.ruleDatas = {};
    },
    //添加节点
    nodeAddFunc (val) {
      this.nodeSaveFlag = val;
      //判断数据选择
      if (val != '1') {
        let selection = this.$refs.multipleSceneNodeTable.selection;
        if (selection.length < 1) {
          return this.$message.warning("请选择一条数据");
        } else if (selection.length > 1) {
          return this.$message.warning("只能选择一条数据");
        } else {
          this.nodeCode = selection[0].nodeCode;
        }
      } else {
        this.nodeCode = "";
      }
      if (val == '5') {
        this.nodeCode = "";
      }
      let parentQueryData = {
        sceneCode: this.sceneCode,
        curNodeCode:this.nodeCode
      }
      //父级节点赋值
      ruleScene.comboBySceneNode(parentQueryData).then(res=> {
        if (res.code == 200) {
          this.parentNodeList = res.datas;
        }
      });
      //列表变化
      let arr = []
      arr = this.tableSceneNodeData.filter(item => {
          return item.saveData == '新增' || item.saveData == '编辑' || item.saveData == '复制'
      });
      if (arr.length == 0) {
        if(val == 1) {//新增
          this.addNodeData.nodeCode = "";
          this.addNodeData.nodeName = "";
          this.addNodeData.parentNode = "";
          this.addNodeData.descn = "";
          this.tableSceneNodeData.push({
            nodeCode: '',
            nodeName: '',
            parentNode: '',
            descn: '',
            saveData: '新增'
          })
        } else if (val == 2) {//编辑
          let selection = this.$refs.multipleSceneNodeTable.selection;
          this.tableSceneNodeData.forEach((element, index) => {
            if (element.nodeCode == selection[0].nodeCode) {
              //this.tableSceneNodeData[index].saveData = '编辑'
              this.$set(this.tableSceneNodeData[index],'saveData','编辑')
            }

          });
        }  else if (val == 5) {//复制
          let selection = this.$refs.multipleSceneNodeTable.selection
          this.copyNodeData = {...selection[0]};
          this.copyNodeData.nodeCode = '';
          this.copyNodeData.parentNode = '';
          this.copyNodeData.parentName = '';
          this.saveData = "复制";
          this.tableSceneNodeData.push({
            nodeCode: '',
            nodeName: '',
            parentNode: '',
            descn: '',
            saveData: '复制'
          })
        }
      } else {
        this.$message({
          message: '当前有正在编辑！',
          type: 'warning'
        })
      }
    },
    //取消
    editCancel() {
        let arr = []
        arr = this.tableSceneNodeData.filter(item => {
            return item.saveData == '新增' || item.saveData == '编辑' || item.saveData == '复制'
        })
        if (arr.length == 0) {
            this.$message({
                message: '当前无正在编辑！',
                type: 'warning'
            })
        } else {
            this.searchSceneNodeFunc()
        }
        this.addNodeData  = {
          nodeCode: '',
          nodeName: '',
          ruleSceneCode: '',
          parentNode: '',
          descn: ''
        }
    },
    //保存场景节点
    saveSceneNode() {
      let arr = []
      arr = this.tableSceneNodeData.filter(item => {
          return item.saveData == '新增' || item.saveData == '编辑' || item.saveData == '复制'
      })
      if (arr.length == 0) {
          this.$message({
              message: '当前无正在编辑！',
              type: 'warning'
          })
      } else {
          this.checkNode = false;
          if (this.nodeSaveFlag == '2') {//编辑
              let selection = this.$refs.multipleSceneNodeTable.selection;
              let data = selection[0];
              data.ruleSceneCode = this.sceneCode;
              //this.checkNodeCode(data.nodeCode);
              if (this.checkNodeDetail(data)) {
                ruleScene.saveSceneNode(data).then(res => {
                  if (res.code == 200) {
                      this.$message.success("保存成功");
                      this.searchSceneNodeFunc()
                  }
                })
              }
          } else if (this.nodeSaveFlag == '1') {//新增
              this.addNodeData.ruleSceneCode = this.sceneCode;
              let data = this.addNodeData;
              let checkData = {
                nodeCode:data.nodeCode
              };
              if(this.checkNodeDetail(data)) {
                  ruleScene.checkNodeCode(checkData).then(res => {
                    if (res.code == 200&&res.message != null && res.message != '') {
                      this.$message.warning("英文名已存在");
                    } else {
                      ruleScene.saveSceneNode(data).then(res => {
                        if (res.code == 200) {
                            this.$message.success("保存成功");
                            this.searchSceneNodeFunc()
                        }
                      })
                    }
                });
              }
              
          } else if (this.nodeSaveFlag == '5') {//复制
            this.copyNodeData.ruleSceneCode = this.sceneCode;
            let data = this.copyNodeData;
            let checkData = {
              nodeCode:data.nodeCode
            };
            if(this.checkNodeDetail(data)) {
              ruleScene.checkNodeCode(checkData).then(res => {
                if (res.code == 200&&res.message != null && res.message != '') {
                  this.$message.warning("英文名已存在");
                } else {
                  ruleScene.saveSceneNode(data).then(res => {
                    if (res.code == 200) {
                        this.$message.success("保存成功");
                        this.searchSceneNodeFunc()
                    }
                  })
                }
              });
            }
          }
      }
    },
    checkNodeDetail(data) {
      let nodeCode = data.nodeCode;
      if(nodeCode.length == 0) {
        this.$message.warning("英文名不能为空");
        return false;
      }
      let checkRule = /^[a-zA-Z0-9_-]{1,30}$/;
      if(!checkRule.test(nodeCode)) {
        this.$message.warning("英文名必须是英文或数字且长度不能超过30");
        return false;
      }
      let nodeName = data.nodeName;
      if(nodeName.length == 0) {
        this.$message.warning("节点名称不能为空");
        return false;
      }
      return true;
    },
    checkNodeCode(val) {
      let data = {
        nodeCode:val
      };
      ruleScene.checkNodeCode(data).then(res => {
          if (res.code == 200&&res.message != null && res.message != '') {
            this.checkNode = true;
            this.$message.success("英文名已存在");
          } else {
            this.checkNode = false;
          }
      });
    },
    //   点击行选中
    authorizeForSceneNode(row) {
      //行选中设置
      if (this.$refs.multipleSceneNodeTable) {
          this.$refs.multipleSceneNodeTable.clearSelection()
      }
      this.$refs.multipleSceneNodeTable.toggleRowSelection(row, true);
      this.nodeCode = row.nodeCode;
    },
    changeRule() {
      this.ruleDatas = undefined;
      this.ruleDatas = new Array();
      this.selectRule = undefined;
      this.selectRule = new Array();
      //获取未选规则
      let sceneData = {
        sceneCode:this.sceneCode
      }
      ruleScene.listByScene(sceneData).then(res => {
        if (res.code === 200) {
          this.ruleDatas = res.datas;
          //获取已选规则
          let data= {
            nodeCode:this.nodeCode
          }
          ruleScene.listByNode(data).then(resSelect => {
            if (resSelect.code === 200) {
              if (resSelect.datas != null&&resSelect.datas != undefined&&resSelect.datas.length > 0) {
                for(let i = 0;i<resSelect.datas.length;i++) {
                  this.ruleDatas.push(resSelect.datas[i]);
                  this.selectRule.push(resSelect.datas[i].ruleCode);
                }
              }
              if(this.operateType == "3") {
                this.ruleDatas.forEach(item=>{
                  this.$set(item,'disabled',true)
                })
              }
            }
          });
        }
      });
    },
    saveRuleNode() {
      let ruleCodes = "";
      for(let i = 0;i < this.selectRule.length;i++) {
        ruleCodes += this.selectRule[i] + ",";
      }
      if(ruleCodes.length > 0) {
        ruleCodes = ruleCodes.substr(0,ruleCodes.length-1);
      }
      let data= {
        nodeCode:this.nodeCode,
        ruleCodes:ruleCodes
      }
      ruleScene.saveRuleNode(data).then(res => {
        if (res.code === 200) {
          this.$message.success("保存成功");
        } else {
          this.$message.error(res.message || "保存失败");
        }
      });
    },
    //删除节点
    delNodeFunc() {
      let arr = []
      arr = this.tableSceneNodeData.filter(item => {
          return item.saveData == '新增' || item.saveData == '编辑' || item.saveData == '复制'
      })
      if (arr.length != 0) {
        return this.$message.warning("有正在编辑的数据，不能删除");
      }
      let selection = this.$refs.multipleSceneNodeTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中场景节点吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = { ids: selection.map(v => v.nodeCode) };
          ruleScene.removeAndCheck(data).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchSceneNodeFunc();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //显示规则配置
    showRule() {
      this.hideRuleIcon=true;
      this.showRuleIcon=false;
      this.ruleLeftWidth = 12;
      this.ruleCon=true;
    },
    //隐藏规则配置
    hideRule() {
      this.showRuleIcon=true;
      this.hideRuleIcon=false;
      this.ruleLeftWidth = 22;
      this.ruleCon=false;
    },
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    handleSceneNodeSizeChange(val) {
      this.searchSceneNodeForm.size = val;
      console.log(val, "每页数");
      this.searchSceneNodeFunc();
    },
    handleSceneNodeCurrentChange(val) {
      this.searchSceneNodeForm.page = val;
      console.log(val, "当前页");
      this.searchSceneNodeFunc();
    }
  }
};
</script>

<style lang="scss">
.dialogSearchBox {
  header {
    text-align: center;
    span {
      margin: 0 20px;
    }
  }
}
.icon-arrow{
  float: right;
}
.el-transfer .el-input--small {
  width:auto !important;
}
.el-transfer .el-button {
  display: block;
  margin-left: 0;
  min-width: 10px;
}
</style>